<template>
  <div class="all" v-title data-title="搜索">
    <div class="search">
      <div style="padding-left: 5%; padding-top: 10px; width: 25%">
        <span style="float: left">
          <el-image
            style="width: 90%; height: 80px"
            src="http://8.130.171.48:8080/img/logo.jpg"
            fit="fill"
          >
          </el-image>
        </span>
      </div>
      <div
        class="searchInput"
        style="
          width: 50%;
          text-align: center;
          margin: 0px auto;
          padding-top: 20px;
        "
      >
        <el-input
          prefix-icon="el-icon-search"
          placeholder="搜索商品"
          v-model="input"
          @keyup.enter.native="search"
          style="width: 80%"
        >
        </el-input>
        <el-button @click="search">搜索</el-button>
      </div>
    </div>
    <br />
    <div class="leftPlace" :class="flag ? 'active' : 'leftPlace'">
      <!-- 左侧区域 -->
      <div
        style="
          padding-left: 5px;
          padding-top: 10px;
          padding-bottom: 10px;
          border-bottom: 1px solid rgb(192, 192, 241);
        "
      >
        <h4 style="margin: 0; color: black">分类筛选</h4>
      </div>
      <div
        class="inner"
        style="text-align: right; margin-right: 5px; margin-top: 10px"
      >
        <!-- fromPrice 最低价 1 toPrice 最高价 1-->
        筛选方式：
        <el-select
          v-model="params.sort"
          placeholder="请选择"
          style="width: 90px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <br />
        <br />
        <div>
          最低价：
          <el-input
            v-model="params.fromPrice"
            style="width: 90px; font-size: 10px"
          ></el-input>
        </div>
        <br />
        <div>
          最高价：
          <el-input
            v-model="params.toPrice"
            style="width: 90px; font-size: 10px"
          ></el-input>
        </div>
        <br />
        <div>
          分类：
          <el-cascader
            style="width: 90px"
            v-model="params.categoryId"
            :options="productTree"
          >
          </el-cascader>
        </div>
        <br />
        <div style="margin: auto; text-align: center">
          <el-button size="small" type="info" @click="choose"> 筛选 </el-button>
        </div>
      </div>
    </div>
    <div class="searchResult" :class="flag ? 'active' : 'leftPlace'">
      <!-- 搜索结果展示 -->
      <div
        v-show="goodsList.searchGoodsList"
        style="width: 100%; text-align: center"
      >
        <el-table :data="goodsList.searchGoodsList">
          <el-table-column width="200px">
            <template slot-scope="scope" style="text-align: center">
              <div
                style="
                  width: 150px;
                  height: 150px;
                  text-align: center;
                  border: solid 1px #ddd;
                  margin-left: 30px;
                "
              >
                <el-popover
                  placement="right-start"
                  trigger="hover"
                  style="text-align: center"
                >
                  <img
                    :src="scope.row.imageURL"
                    style="width: 250px; height: 250px; cursor: pointer"
                    @click="goShop(scope.row.id, scope.row.name)"
                  />
                  <img
                    :src="scope.row.imageURL"
                    slot="reference"
                    style="width: 130px; height: 145px; cursor: pointer"
                    @click="goShop(scope.row.id, scope.row.name)"
                  />
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="530px">
            <template slot-scope="scope">
              <div style="border-right: solid 1px #999; padding-right: 2%">
                <!-- 商品信息 -->
                <div style="color: #8c222c; font-weight: 700">
                  <!-- 第一行：商品名称+品相 -->
                  <el-link
                    type="danger"
                    style="font-weight: 700; font-size: 18px"
                    @click="goShop(scope.row.id, scope.row.name)"
                    >{{ scope.row.name }}</el-link
                  >
                  <span
                    style="
                      float: right;
                      color: #999;
                      font-weight: 400;
                      font-size: 12px;
                    "
                    >{{ scope.row.appearance }}</span
                  >
                </div>
                <div
                  style="
                    font-size: 12px;
                    line-height: 16px;
                    color: #333;
                    margin-top: 12px;
                  "
                >
                  <!-- 相关信息 -->
                  <span>{{ scope.row.author }}著/</span>
                  <span>{{ scope.row.translator }}译；</span><br />
                  <span>
                    {{ scope.row.pressHorse
                    }}{{ scope.row.publicationDate }}出品/
                  </span>
                  <span>{{ scope.row.updateDate }}更新/</span>
                  <span>{{ scope.row.category }}</span>
                </div>
                <div style="font-size: 12px; margin: 8px 0px">
                  <!-- 浏览量 -->
                  <span>浏览次数：{{ scope.row.viewCount }}次</span>

                  <!-- 卖家信息 -->
                  <!-- <div style="color: #999">卖家信息：</div>
                  <span style="color: #999; display: inline-block">
                    {{ scope.row.nickname }}：
                  </span>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <el-rate
                    v-model="scope.row.value"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                    style="display: inline-block"
                  >
                  </el-rate>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <el-link
                    type="primary"
                    @click="goSell()"
                    style="display: inline-block; text-align: right"
                  >
                    <i class="el-icon-s-comment"></i>
                    联系卖家</el-link
                  > -->
                </div>
                <br />
              </div>
            </template>
          </el-table-column>
          <el-table-column width="220px" style="background-color: #f2f1ea">
            <template slot-scope="scope">
              <div
                style="
                  font-weight: 400;
                  color: #999;
                  font-size: 14px;
                  text-align: right;
                  top: 0px;
                "
              >
                <!-- 价格 -->
                价格：
                <span style="font-size: 22px; font-weight: 700px; color: red"
                  >¥{{ scope.row.price }}</span
                >
              </div>
              <div style="text-align: right; margin-top: 75px">
                <!-- 操作 -->
                <el-button
                  type="primary"
                  @click="buy(scope.row.id, scope.row.userId)"
                  icon="el-icon-shopping-bag-1"
                  size="small"
                  plain
                  >购买</el-button
                >
                <el-button
                  @click="addToShoppingCar(scope.row.id, 1)"
                  type="danger"
                  size="small"
                  icon="el-icon-shopping-cart-2"
                  plain
                >
                  加入购物车
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.currentPage"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="goodsList.recordCound"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import base from "../../api/base";
import api from "../../api";
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState("login", ["user"]),
  },
  // 请求:searchGoods(商品名productName，最低价fromPrice（不传默认为0），最高价toPrice(不传，默认为1000000），
  // 筛选分类categoryId，筛选卖家userId，最早更新时间fromUpdateTime(不传，默认为2000/01/01),
  // 最晚更新时间toUpdateTime(不传，默认为2025/01/01),最早出版时间fromPublicDate（不传，默认为1900/01/01)，
  // 最晚出版时间toPublicDate(不传，默认为2025/01/01),筛选作者author，筛选品相appearance，筛选出版社pressHorse，
  // 排序方式sort，第几页pageIndex，页大小pageSize（1页显示多少个搜索结果））
  // -----排序方式 asc 代表升序，desc代表降序
  // 排序方式的可选值（中间为空格）：product_price asc(价格升序）,product_price desc（价格降序）
  //                   product_visit desc(人气降序）
  //                   product_updatetime asc/desc(更新时间升序/降序）
  //                   product_publication_date asc/desc(出版时间升序/降序）

  data() {
    return {
      productTree: [],
      input: "",
      goodsList: [],
      userId: "",
      params: {
        productName: "",
        fromPrice: 0,
        toPrice: 0,
        categoryId: [],
        sort: "product_visit desc",
        pageIndex: 0,
        pageSize: 10,
        currentPage: 1, //初始页
      },
      options: [
        {
          value: "product_price asc",
          label: "价格升序",
        },
        {
          value: "product_price desc",
          label: "价格降序",
        },
        {
          value: "product_visit asc",
          label: "人气升序",
        },
        {
          value: "product_visit desc",
          label: "人气降序",
        },
        // {
        //   value: " product_updatetime asc",
        //   label: "更新时间升序",
        // },
        // {
        //   value: " product_updatetime desc",
        //   label: "更新时间降序",
        // },
        // {
        //   value: "product_publication_date asc",
        //   label: "出版时间升序",
        // },
        // {
        //   value: "product_publication_date desc",
        //   label: "出版时间降序",
        // },
      ],
      scroll: "",
      flag: false,
    };
  },
  methods: {
    // 初始页currentPage、初始每页数据数pageSize和数据data
    handleSizeChange: function (size) {
      this.params.pageSize = size;
      this.params.currentPage = 1;
      this.params.pageIndex = 0;
      this.$router.push({
        path: "/search",
        query: {
          input: this.params.productName,
          params: JSON.stringify(this.params),
        },
      });
      location.reload();
    },
    handleCurrentChange: function (currentPage) {
      this.params.currentPage = currentPage;
      this.params.pageIndex = currentPage - 1;
      // this.find();
      this.$router.push({
        path: "/search",
        query: {
          input: this.params.productName,
          params: JSON.stringify(this.params),
        },
      });
      location.reload();
    },
    searchGoods(params) {
      this.$http
        .get(base.baseUrl + "/searchGoods", {
          params,
        })
        .then((res) => {
          this.goodsList = res.data;
          for (let i = 0; i < this.goodsList.searchGoodsList.length; i++) {
            this.goodsList.searchGoodsList[i].imageURL =
              base.baseUrl + this.goodsList.searchGoodsList[i].imageURL;
          }
          console.log(this.goodsList);
        });
    },
    search() {
      this.params.productName = this.input;
      this.params.currentPage = 1;
      this.params.pageIndex = 0;
      this.$router.push({
        path: "/search",
        query: {
          input: this.input,
          params: JSON.stringify(this.params),
        },
      });
      location.reload();
    },
    // 筛选
    find() {
      let param = {};
      if (this.params.categoryId.length > 0) {
        param.categoryId =
          this.params.categoryId[this.params.categoryId.length - 1];
      }
      if (this.params.fromPrice != 0) {
        param.fromPrice = this.params.fromPrice;
      }
      if (this.params.toPrice != 0) {
        param.toPrice = this.params.toPrice;
      }
      param.sort = this.params.sort;
      param.pageSize = this.params.pageSize;
      param.pageIndex = this.params.currentPage - 1;
      param.productName = this.input;
      console.log(param);
      this.searchGoods(param);
    },
    goShop(goodId, name) {
      let routeUrl = this.$router.resolve({
        path: "/showgoods",
        query: {
          goodId: goodId,
          name: name,
        },
      });
      window.open(routeUrl.href, "_blank");
    },
    addToShoppingCar(goodId, num) {
      //添加到购物车addToShoppingCar
      if (this.userId == "") {
        this.$router.push("/login");
        return;
      } else {
        if (this.userId != null) {
          // 这里要不null改成卖家信息的id
          this.$http
            .get(base.baseUrl + "/good/addToShoppingCar", {
              params: { goodId: goodId, userId: this.userId, count: num },
            })
            .then((res) => {
              if (res.data == 0) {
                this.$message({
                  showClose: true,
                  message: "添加失败",
                  type: "false",
                });
              } else {
                this.$message({
                  showClose: true,
                  message: "添加成功",
                  type: "success",
                });
              }
            });
        } else {
          this.$message({
            showClose: true,
            message: "不能把自己的商品加入购物车",
            type: "false",
          });
        }
      }
    },
    choose() {
      this.$router.push({
        path: "/search",
        query: {
          input: this.params.productName,
          params: JSON.stringify(this.params),
        },
      });
      location.reload();
    },
    // 购买
    buy(goodId, sellerId) {
      //购买
      if (this.userId == "") {
        this.$router.push({
          path: "/login",
          query: {
            perPath: window.location.hash,
          },
        });
        return;
      } else {
        if (this.userId != sellerId) {
          let goodIds = [];
          goodIds.push(goodId);
          let routeUrl = this.$router.resolve({
            path: "/order",
            query: {
              userId: this.userId,
              goodId: goodIds,
              num: 1,
            },
          });
          window.open(routeUrl.href, "_blank");
        } else {
          this.$message({
            showClose: true,
            message: "不能购买自己的商品",
            type: "error",
          });
        }
      }
    },
    handleScroll() {
      this.scroll =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (this.scroll >= 200) {
        this.flag = true;
      } else {
        this.flag = false;
      }
    },
  },
  created() {
    if (!this.$route.query.input) {
      this.$router.push("/");
    }
    this.input = this.$route.query.input;
    if (this.$route.query.params) {
      this.params = JSON.parse(this.$route.query.params);
    } else {
      this.params.productName = this.input;
      this.$router.push({
        path: "/search",
        query: { input: this.$route.query.input, params: this.params },
      });
    }
    this.userId = this.user.userId;
    api.getAllCategories().then((res) => {
      this.productTree = JSON.parse(
        JSON.stringify(res.data)
          .replace(/id/g, "value")
          .replace(/name/g, "label")
          .replace(/subList/g, "children")
      );
    });
    this.find();
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
};
</script>

<style lang="less">
.all {
  background-color: white;
  position: fixed;
  height: 100%;
  width: 100%;
  position: relative;
  min-height: 500px;
  .search {
    // position: fixed;
    height: 100px;
    width: 100%;
    border-bottom: solid 2px #f80707;
  }
  .leftPlace {
    text-align: right;
    width: 12.5%;
    display: inline-block;
    vertical-align: top;
    background-color: snow;
    border: 1px solid rgb(192, 192, 241);
    height: 320px;
    text-align: left;
    font-weight: 400px;
    color: #9999;
    font-size: 13px;
    margin-right: 20px;
    .inner {
      .el-input__inner {
        padding: 0 10px;
      }
    }
  }
  .leftPlace.active {
    position: fixed;
    left: 63px;
    top: 20px;
    text-align: right;
    width: 12.5%;
    display: inline-block;
    vertical-align: top;
    background-color: snow;
    border: 1px solid rgb(192, 192, 241);
    height: 320px;
    text-align: left;
    font-weight: 400px;
    color: #9999;
    font-size: 13px;
    margin-right: 20px;
    .inner {
      .el-input__inner {
        padding: 0 10px;
      }
    }
  }
  .searchResult {
    padding-bottom: 10px;
    border: 1px solid rgb(192, 192, 241);
    // margin-left: 100px;
    // position: fixed;
    width: 75%;
    display: inline-block;
    vertical-align: top;
    min-height: 500px;
    .el-table {
      margin-left: 1%;
      width: 98%;
      margin-right: 0;
      margin-top: 10px;
      .el-table__header-wrapper {
        display: none;
      }
      .el-table__body {
        width: 100% !important;
      }
    }
  }
  .searchResult.active {
    padding-bottom: 10px;
    border: 1px solid rgb(192, 192, 241);
    // margin-left: 100px;
    // position: fixed;
    margin-left: 12.5%;
    width: 75%;
    display: inline-block;
    vertical-align: top;
    min-height: 500px;
    .el-table {
      margin-left: 1%;
      width: 98%;
      margin-right: 0;
      margin-top: 10px;
      .el-table__header-wrapper {
        display: none;
      }
      .el-table__body {
        width: 100% !important;
      }
    }
  }
}
</style>